/*
 * NewProjectDialog.java
 *
 * Created on February 13, 2008, 4:06 AM
 */

package gui.project;

import datamodel.WSFProject;
import datamodel.WSFProjectInfo;
import exceptions.UnSupportedException;
import gui.WSFApplication;
import gui.WSFApplicationView;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.wsdl.WSDLException;
import javax.xml.stream.XMLStreamException;
import org.apache.log4j.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.Task;

/**
 *
 * @author  chang
 */
public class NewProjectDialog extends javax.swing.JDialog {
    
    private static Logger logger = Logger.getLogger(NewProjectDialog.class);
    
    /** Creates new form NewProjectDialog */
    public NewProjectDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        enableOKButton();
        
        this.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                projectNameTextField.setText("");
                wsdlURLTextField.setText("");
            }
        });
    }
    
    @Action
    public void cancelButtonPressed(){
        this.dispose();
    }
    
    @Action
    public Task creatProject() {
        logger.info("Create Project: name: " + projectNameTextField.getText());
        logger.info("Create Project: wsdl: " + wsdlURLTextField.getText());
        this.okButton.setEnabled(false);
        this.cancelButton.setEnabled(false);
        return new CreateProject(WSFApplication.getApplication());
    }

    public class CreateProject extends Task<WSFProject, Void> {

        private WSFApplication app;
        private File path;
        private String projectName;
        private String wsdlURL;
        private WSFProjectInfo projectInfo;

        public CreateProject(WSFApplication app) {

            super(app);

            this.app = app;
            this.projectName = projectNameTextField.getText();
            this.wsdlURL = wsdlURLTextField.getText();
            this.path = new File(app.getWSFConfiguration().getProjectsDirectory().getAbsolutePath()+File.separator+projectName);
            
            projectInfo = new WSFProjectInfo(projectName, wsdlURL);
        }

        @Override
        protected WSFProject doInBackground() throws WSDLException, UnSupportedException, XMLStreamException, Exception {
            return new WSFProject(projectName, path, wsdlURL);
        }

        @Override
        protected void succeeded(WSFProject project) {
            try{
                project.save();
                app.getWSFConfiguration().addProject(projectInfo);
                app.getProjects().add(project);
                app.getWSFConfiguration().saveChanges();
                ((WSFApplicationView)app.getMainView()).addNewProjectToTree(project);
                logger.info("Create Project: created");
            } catch (IOException ex) {
                logger.debug(ex);
            } catch (XMLStreamException ex) {
                logger.debug(ex);
            } catch (Exception ex) {
                logger.debug(ex);
            } 
            
            close();
        }

        @Override
        protected void failed(Throwable cause) {
            
            logger.error(cause.getMessage());
            showMessage("Unexpected Error occured!" + cause.getMessage());
            StringWriter sWriter = new StringWriter();
            cause.printStackTrace(new PrintWriter(sWriter));
            logger.error(sWriter.toString());
            
            okButton.setEnabled(true);
            cancelButton.setEnabled(true);
        }

        @Override
        protected void finished() {
        }
    }
    
    private void showMessage(String msg) {
        JOptionPane.showMessageDialog(this, msg, "Information", JOptionPane.INFORMATION_MESSAGE);
    }
    
    @Action
    public void close(){
        projectNameTextField.setText("");
        wsdlURLTextField.setText("");

        okButton.setEnabled(true);
        cancelButton.setEnabled(true);

        this.dispose();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        wsdlURLTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        projectNameTextField = new javax.swing.JTextField();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gui.WSFApplication.class).getContext().getResourceMap(NewProjectDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        wsdlURLTextField.setText(resourceMap.getString("wsdlURLTextField.text")); // NOI18N
        wsdlURLTextField.setName("wsdlURLTextField"); // NOI18N
        wsdlURLTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                wsdlURLTextFieldFocusLost(evt);
            }
        });
        wsdlURLTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                wsdlURLTextFieldKeyTyped(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        projectNameTextField.setText(resourceMap.getString("projectNameTextField.text")); // NOI18N
        projectNameTextField.setName("projectNameTextField"); // NOI18N
        projectNameTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                projectNameTextFieldKeyReleased(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gui.WSFApplication.class).getContext().getActionMap(NewProjectDialog.class, this);
        okButton.setAction(actionMap.get("creatProject")); // NOI18N
        okButton.setText(resourceMap.getString("okButton.text")); // NOI18N
        okButton.setName("okButton"); // NOI18N

        cancelButton.setAction(actionMap.get("close")); // NOI18N
        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(projectNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
                            .addComponent(wsdlURLTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wsdlURLTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(projectNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void wsdlURLTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_wsdlURLTextFieldFocusLost

            String name = projectNameTextField.getText();
            String path = wsdlURLTextField.getText();
            
        try {
            URI uri = new URI(path);
            if (!path.equalsIgnoreCase("") && name.equalsIgnoreCase("")) {
                name = uri.getPath().replaceAll("^.*/", "").replaceFirst("\\?.*$", "").replaceFirst("\\.[^.]*$", "");
                projectNameTextField.setText(name);
                enableOKButton();
            }
        } catch (URISyntaxException ex) {
            
        }
    }//GEN-LAST:event_wsdlURLTextFieldFocusLost

    private void wsdlURLTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_wsdlURLTextFieldKeyTyped
        enableOKButton();
    }//GEN-LAST:event_wsdlURLTextFieldKeyTyped

    private void projectNameTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_projectNameTextFieldKeyReleased
        enableOKButton();
    }//GEN-LAST:event_projectNameTextFieldKeyReleased
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewProjectDialog dialog = new NewProjectDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    public void enableOKButton(){
        String name = projectNameTextField.getText();
        String path = wsdlURLTextField.getText();
        
        ArrayList<WSFProject> projects = WSFApplication.getApplication().getProjects();
        for(WSFProject project : projects){
            if(project.getName().equalsIgnoreCase(name)){
                okButton.setEnabled(false);
                return;
            }
        }
        
        if(!name.equalsIgnoreCase("") && !path.equalsIgnoreCase(""))
            okButton.setEnabled(true);
        else 
            okButton.setEnabled(false);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton okButton;
    private javax.swing.JTextField projectNameTextField;
    private javax.swing.JTextField wsdlURLTextField;
    // End of variables declaration//GEN-END:variables
    
}
